#include "wn_fs.h"
#include "fsdata.h"
#include <string.h>


#ifndef LWIP_MAX_OPEN_FILES
#define LWIP_MAX_OPEN_FILES     10 //定义最多能打开的文件数目
#endif

//定义文件系统内存分配结构体
struct fs_table {
	struct fs_file file;
	unsigned char inuse;   //0表示未使用,1表示使用
};

struct fs_table fs_memory[LWIP_MAX_OPEN_FILES];


static struct fs_file *fs_malloc(void)
{
	int i;
	for(i = 0; i < LWIP_MAX_OPEN_FILES; i++) 
    {
		if(fs_memory[i].inuse == 0) 
        {
			fs_memory[i].inuse = 1;
			return(&fs_memory[i].file);
		}
	}
	return(NULL);
}

static void fs_free(struct fs_file *file)
{
	int i;
	for(i = 0; i < LWIP_MAX_OPEN_FILES; i++) 
    {
		if(&fs_memory[i].file == file) 
        {
			fs_memory[i].inuse = 0;
			break;
		}
	}
	return;
}

int fs_check(const char *name)
{
	const struct fsdata_file *f;
  
	for(f = FS_ROOT; f != NULL; f = f->next) 
	{
		if (!strcmp(name, (char *)f->name)) 
		{
			return 1;
		}
	}
	return 0;
}

struct fs_file *fs_open(const char *name)
{
	struct fs_file *file;
	const struct fsdata_file *f;
	
	file = fs_malloc();  //申请内存
	if(file == NULL) 
    {
        return NULL;
	}
	
	for(f = FS_ROOT; f != NULL; f = f->next) 
    {
		if (!strcmp(name, (char *)f->name)) 
        {     
			file->data = (const char *)f->data;
			file->len = f->len;
			file->index = 0;
			return file;
		}
	}
	fs_free(file);  //释放file内存
	return NULL;
}

void fs_close(struct fs_file *file)
{
	fs_free(file);  //释放file的内存
}


//读取文件
//参数:file 要读取的文件
//参数:buffer 读取到后存放的缓冲区
//参数:count  要读取的个数
int fs_read(struct fs_file *file, char *buffer, int count)
{
	int read; //实际读取的数据个数
	
	if(file->index == file->len) 
    {
		return -1;
	}
	
	read = file->len - file->index;
	if(read > count) 
    {
		read = count;
	}
	
	memcpy(buffer, (file->data + file->index), read);
	file->index += read;
	
	return(read);  //返回读取的数据个数
}

//文件左对齐
int fs_bytes_left(struct fs_file *file)
{
	return file->len - file->index;
}
